home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1992 June: ROMin Holiday / ADC Developer CD (1992-06) (''ROMin Holiday'')_iso / Developer Connection - 06-1992.iso / Developer Essentials / DTS Sample Code / Macintosh Sample Code / SC.019.TEStyleSample / TEStyleSample.p < prev    next >
Encoding:
Text File  |  1989-09-30  |  51.7 KB  |  1,729 lines  |  [TEXT/MPS ]

  1. {------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Styled TextEdit Sample Application
  6. #
  7. #    TEStyleSample
  8. #
  9. #    TEStyleSample.p    -    Pascal Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    1.0                        10/89
  15. #
  16. #    Components:    TEStyleSample.p            October    1, 1989
  17. #                TEStyleSampleGlue.a        October    1, 1989
  18. #                TEStyleSample.r            October    1, 1989
  19. #                TEStyleSample.h            October    1, 1989
  20. #                PTEStyleSample.make        October    1, 1989
  21. #
  22. #    TEStyleSample is an example application that demonstrates how 
  23. #    to initialize the commonly used toolbox managers, operate 
  24. #    successfully under MultiFinder, handle desk accessories and 
  25. #    create, grow, and zoom windows. Both styled and fundamental TextEdit 
  26. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  27. #    also shows how to create and maintain scrollbar controls as well
  28. #    as implementing a basic printing loop.
  29. #
  30. #    It does not by any means demonstrate all the techniques you 
  31. #    need for a large application. In particular, TEStyleSample does not 
  32. #    cover exception handling, multiple windows/documents, 
  33. #    sophisticated memory management, or undo. All of 
  34. #    these are vital parts of a normal full-sized application.
  35. #
  36. #    This application is an example of the form of a Macintosh 
  37. #    application; it is NOT a template. It is NOT intended to be 
  38. #    used as a foundation for the next world-class, best-selling, 
  39. #    600K application. A stick figure drawing of the human body may 
  40. #    be a good example of the form for a painting, but that does not 
  41. #    mean it should be used as the basis for the next Mona Lisa.
  42. #
  43. #    We recommend that you review this program, TESample or Sample before 
  44. #    beginning a new application. TESample is a simpler version of TEStyleSample
  45. #    without styles and Sample is a simple app. which doesn’t 
  46. #    use TextEdit or the Control Manager.
  47. #
  48. ------------------------------------------------------------------------------}
  49.  
  50.  
  51. PROGRAM TEStyleSample;
  52.  
  53. {Segmentation strategy:
  54.  
  55.  This program consists of three segments. Main contains most of the code,
  56.  including the MPW libraries, and the main program. Initialize contains
  57.  code that is only used once, during startup, and can be unloaded after the
  58.  program starts. %A5Init is automatically created by the Linker to initialize
  59.  globals for the MPW libraries and is unloaded right away.}
  60.  
  61.  
  62. {SetPort strategy:
  63.  
  64.  Toolbox routines do not change the current port. In spite of this, in this
  65.  program we use a strategy of calling SetPort whenever we want to draw or
  66.  make calls which depend on the current port. This makes us less vulnerable
  67.  to bugs in other software which might alter the current port (such as the
  68.  bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  69.  Hopefully, this also makes the routines from this program more self-contained,
  70.  since they don't depend on the current port setting.}
  71.  
  72.  
  73. {Clipboard strategy: 
  74.  
  75.  Under styled TextEdit, TECut and TECopy will write both the text and associated
  76.  style information directly to the desk scrap as types 'TEXT' and 'styl'.
  77.  Instead of using TEToScrap and TEFromScrap, a new routine TEStylPaste, will 
  78.  transfer the text and style from the desk scrap to the document. }
  79.  
  80. {$D+}
  81.  
  82. USES
  83.     MemTypes, QuickDraw, OSIntf, ToolIntf, PackIntf, Traps, MacPrint;
  84.  
  85. CONST
  86.  
  87.     {kTextMargin is the number of pixels we leave blank at the edge of the window.}
  88.     kTextMargin                = 2;
  89.  
  90.     {kMaxOpenDocuments is used to determine whether a new document can be opened
  91.      or created. We keep track of the number of open documents, and disable the
  92.      menu items that create a new document when the maximum is reached. If the
  93.      number of documents falls below the maximum, the items are enabled again.}
  94.     kMaxOpenDocuments        = 1;
  95.     
  96.     {kMaxDocWidth is an arbitrary number used to specify the width of the TERec's
  97.     destination rectangle so that word wrap and horizontal scrolling can be
  98.     demonstrated.}
  99.     kMaxDocWidth            = 576;
  100.     
  101.     {kMinDocDim is used to limit the minimum dimension of a window when GrowWindow
  102.     is called.}
  103.     kMinDocDim                = 64;
  104.     
  105.     {kControlInvisible is used to 'turn off' controls (i.e., cause the control not
  106.     to be redrawn as a result of some Control Manager call such as SetCtlValue)
  107.     by being put into the contrlVis field of the record. kControlVisible is used
  108.     the same way to 'turn on' the control.}
  109.     kControlInvisible        = 0;
  110.     kControlVisible            = $FF;
  111.  
  112.     {kScrollBarAdjust and kScrollBarWidth are used in calculating
  113.     values for control positioning and sizing.}
  114.     kScrollbarWidth            = 16;
  115.     kScrollbarAdjust        = kScrollbarWidth - 1;
  116.  
  117.     {kScrollTweek compensates for off-by-one requirements of the scrollbars
  118.      to have borders coincide with the growbox.}
  119.     kScrollTweek            = 2;
  120.  
  121.     {kCrChar is used to match with a carriage return when calculating the
  122.     number of lines in the TextEdit record. kDelChar is used to check for
  123.     delete in keyDowns.}
  124.     kCRChar                    = 13;
  125.     kDelChar                = 8;
  126.  
  127.     {kButtonScroll is how many pixels to scroll horizontally when the button part
  128.     of the horizontal scrollbar is pressed.}
  129.     kButtonScroll            = 4;
  130.     
  131.     {kMaxTELength is an arbitrary number used to limit the length of text in the TERec
  132.     so that various errors won't occur from too many characters in the text.}
  133.     kMaxTELength            = 32000;
  134.     (* what about that tech note I wrote? is this a valid check anymore? maw *)
  135.  
  136.     {kSysEnvironsVersion is passed to SysEnvirons to tell it which version of the
  137.      SysEnvRec we understand.}
  138.     kSysEnvironsVersion        = 1;
  139.  
  140.     {kOSEvent is the event number of the suspend/resume and mouse-moved events sent
  141.      by MultiFinder. Once we determine that an event is an osEvent, we look at the
  142.      high byte of the message sent to determine which kind it is. To differentiate
  143.      suspend and resume events we check the resumeMask bit.}
  144.     kOSEvent                = app4Evt;    { event used by MultiFinder }
  145.     kSuspendResumeMessage    = 1;        { high byte of suspend/resume event message }
  146.     kResumeMask                = 1;        { bit of message field for resume vs. suspend }
  147.     kMouseMovedMessage        = $FA;        { high byte of mouse-moved event message }
  148.     kNoEvents                = 0;        {no events mask}
  149.  
  150.     {kMinHeap - This is the minimum result from the following
  151.      equation:
  152.             
  153.             ORD(GetApplLimit) - ORD(ApplicZone)
  154.             
  155.      for the application to run. It will insure that enough memory will
  156.      be around for reasonable-sized scraps, FKEYs, etc. to exist with the
  157.      application, and still give the application some 'breathing room'.
  158.      To derive this number, we ran under a MultiFinder partition that was
  159.      our requested minimum size, as given in the 'SIZE' resource.}
  160.      
  161.     kMinHeap    = 29 * 1024; 
  162.  
  163.     {kMinSpace - This is the minimum result from PurgeSpace, when called
  164.      at initialization time, for the application to run. This number acts
  165.      as a double-check to insure that there really is enough memory for the
  166.      application to run, including what has been taken up already by
  167.      pre-loaded resources, the scrap, code, and other sundry memory blocks.}
  168.      
  169.     kMinSpace    = 20 * 1024;
  170.     
  171.     {kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions.}
  172.     kExtremeNeg        = -32768;
  173.     kExtremePos        = 32767 - 1;    { required for old region bug }
  174.     
  175.     {kTESlop provides some extra security when pre-flighting edit commands.}
  176.     kTESlop            = 1024;
  177.  
  178.     {kErrStrings is the resource ID for the error strings STR# resource.}
  179.     kErrStrings        = 128;
  180.  
  181.     { The following are indicies into STR# resources. }
  182.     eWrongMachine    = 1;
  183.     eSmallSize        = 2;
  184.     eNoMemory        = 3;
  185.     eNoSpaceCut        = 4;
  186.     eNoCut            = 5;
  187.     eNoCopy            = 6;
  188.     eExceedPaste    = 7;
  189.     eNoSpacePaste    = 8;
  190.     eNoWindow        = 9;
  191.     eExceedChar        = 10;
  192.     eNoPaste        = 11;
  193.     
  194.     
  195.     { The following constants are all resource IDs, corresponding to their resources }
  196.     
  197.     rMenuBar    = 128;                { application's menu bar }
  198.     rAboutAlert    = 128;                { about alert }
  199.     rUserAlert    = 129;                { user error alert }
  200.     rDocWindow    = 128;                { application's window }
  201.     
  202.     rVScroll    = 128;                { vertical scrollbar control }
  203.     rHScroll    = 129;                { horizontal scrollbar control }
  204.  
  205.  
  206.     { The following constants are all menu and item IDs corresponding to their resources }
  207.     
  208.     mApple        = 128;                { Apple menu }
  209.     iAbout        = 1;
  210.  
  211.     mFile        = 129;                { File menu }
  212.     iNew        = 1;
  213.     iClose        = 4;
  214.     iPageSetup    = 9;                { Added for TEStyleSample }
  215.     iPrint        = 10;                { Added for TEStyleSample }
  216.     iQuit        = 12;
  217.  
  218.     mEdit        = 130;                { Edit menu }
  219.     iUndo        = 1;
  220.     iCut        = 3;
  221.     iCopy        = 4;
  222.     iPaste        = 5;
  223.     iClear        = 6;
  224.     iSelectAll    = 8;                { Added for TEStyleSample }
  225.     
  226.     mFont         = 131;                { Font menu-added for TEStyleSample }
  227.     
  228.     mFontSize     = 132;                { Font size menu-added for TEStyleSample }
  229.     iNine        = 1;
  230.     iTen        = 2;
  231.     iTwelve        = 3;
  232.     iFourteen    = 4;
  233.     iEighteen    = 5;
  234.     iTwoFour    = 6;
  235.     
  236.     mStyle         = 133;                { Style menu-added for TEStyleSample }
  237.     iPlain         = 1;
  238.     iBold         = 3;
  239.     iItalic        = 4;
  240.     iUnderline     = 5;
  241.     iOutline     = 6;
  242.     iShadow     = 7; 
  243.     
  244.     {kDITop and kDILeft are used to locate the Disk Initialization dialogs.}
  245.     kDITop        = $0050;
  246.     kDILeft        = $0070;
  247.  
  248.     
  249. TYPE
  250.     {A DocumentRecord contains the WindowRecord for one of our document windows,
  251.      as well as the TEHandle for the text we are editing. We have added fields to
  252.      hold the ControlHandles to the vertical and horizontal scrollbars and to hold
  253.      the address of the default clikLoop that gets attached to a TERec when you call
  254.      TEAutoView. Other document fields can be added to this record as needed. For
  255.      a similar example, see how the Window Manager and Dialog Manager add fields
  256.      after the GrafPort.}
  257.     DocumentRecord        = RECORD
  258.         docWindow        : WindowRecord;
  259.         docTE            : TEHandle;
  260.         docVScroll        : ControlHandle;
  261.         docHScroll        : ControlHandle;
  262.         docClik            : ProcPtr;
  263.     END;
  264.     DocumentPeek        = ^DocumentRecord;
  265.  
  266.  
  267. VAR
  268.     {The "g" prefix is used to emphasize that a variable is global.}
  269.     gMac                : SysEnvRec;    { set up by Initialize }
  270.     gHasWaitNextEvent    : BOOLEAN;        { set up by Initialize }
  271.     gInBackground        : BOOLEAN;        { maintained by Initialize and DoEvent }
  272.     gNumDocuments        : INTEGER;        { maintained by Initialize, DoNew, and DoCloseWindow }
  273.     
  274.     {New globals to support printing and style selection }
  275.     gTxStyle             : TextStyle;    { holds style selected, plain default, maintained by DoMenuCommand }
  276.     gFontName             : Str255;        { name of font selected, app font default, maintained by DoMenuCommand }
  277.     gFontID             : INTEGER;        { ID of font selected, app font default, maintained by DoMenuCommand }
  278.     gFontSize             : LONGINT;        { font size selected, 12 pt default, maintained by DoMenuCommand }
  279.     gPrinterRecord        : THPrint;        { print handle, maintained by printText }
  280.     gPrinterPort        : TPPrPort;        { pointer to Print Manager's GrafPort }
  281.  
  282.  
  283.  
  284. {$S Initialize}
  285. FUNCTION TrapAvailable(tNumber: INTEGER; tType: TrapType): BOOLEAN;
  286.  
  287. {Check to see if a given trap is implemented. This is only used by the
  288.  Initialize routine in this program, so we put it in the Initialize segment.
  289.  The recommended approach to see if a trap is implemented is to see if
  290.  the address of the trap routine is the same as the address of the
  291.  Unimplemented trap.}
  292. {Needs to be called after call to SysEnvirons so that it can check
  293.  if a ToolTrap is out of range of a pre-MacII ROM.}
  294.  
  295. BEGIN
  296.     IF (tType = ToolTrap) &
  297.         (gMac.machineType > envMachUnknown) &
  298.         (gMac.machineType < envMacII) THEN BEGIN        {it's a 512KE, Plus, or SE}
  299.         tNumber := BAND(tNumber, $03FF);
  300.         IF tNumber > $01FF THEN                            {which means the tool traps}
  301.             tNumber := _Unimplemented;                    {only go to $01FF}
  302.     END;
  303.     TrapAvailable := NGetTrapAddress(tNumber, tType) <>
  304.                         GetTrapAddress(_Unimplemented);
  305. END; {TrapAvailable}
  306.  
  307.  
  308. {$S Main}
  309. FUNCTION IsDAWindow( window : WindowPtr ) : BOOLEAN;
  310.  
  311. {  Check if a window belongs to a desk accessory. }
  312.  
  313. BEGIN { IsDAWindow }
  314.     IF window = NIL THEN
  315.         IsDAWindow := FALSE
  316.     ELSE    { DA windows have negative windowKinds }
  317.         IsDAWindow := WindowPeek( window )^.windowKind < 0;
  318. END; { IsDAWindow }
  319.  
  320.  
  321.  
  322. {$S Main}
  323. FUNCTION IsAppWindow( window : WindowPtr ) : BOOLEAN;
  324.  
  325. {  Check if a window belongs to the application. }
  326.  
  327. BEGIN { IsAppWindow }
  328.     IF window = NIL THEN
  329.         IsAppWindow := FALSE
  330.     ELSE    { application windows have non-negative windowKinds }
  331.         IsAppWindow := WindowPeek( window )^.windowKind >= 0;
  332. END; { IsAppWindow }
  333.  
  334.  
  335.  
  336. {$S Main}
  337. PROCEDURE AlertUser( error : INTEGER );
  338.  
  339. {  Display an alert that tells the user an error occurred, then exit the program }
  340.  
  341. VAR
  342.     itemHit    : INTEGER;
  343.     message    : Str255;
  344.  
  345. BEGIN { AlertUser }
  346.     SetCursor( arrow );
  347.     GetIndString( message, kErrStrings, error );
  348.     ParamText(message, '', '', '');
  349.     itemHit := Alert( rUserAlert, NIL );
  350. END; { AlertUser }
  351.  
  352.  
  353.  
  354. {$S Main}
  355. PROCEDURE GetTERect( window : WindowPtr; VAR teRect : Rect);
  356.  
  357. {   return a rectangle that is inset from the portRect by the size of
  358.     the scrollbars and a little extra margin. }
  359.  
  360. BEGIN { GetTERect }
  361.     teRect := window^.portRect;
  362.     InsetRect( teRect, kTextMargin, kTextMargin );        { adjust for margin }
  363.     teRect.bottom := teRect.bottom - kScrollbarAdjust;    { and for the scrollbars }
  364.     teRect.right := teRect.right - kScrollbarAdjust;
  365. END; { GetTERect }
  366.  
  367.  
  368.  
  369. {$S Main}
  370. FUNCTION DoCloseWindow( window : WindowPtr ) : BOOLEAN;
  371.  
  372. {    Close a window. This handles desk accessory and application windows. }
  373.  
  374. BEGIN { DoCloseWindow }
  375.     DoCloseWindow := TRUE;
  376.     IF IsDAWindow( window ) THEN
  377.         CloseDeskAcc( WindowPeek( window )^.windowKind )
  378.     ELSE IF IsAppWindow( window ) THEN BEGIN
  379.         WITH DocumentPeek( window )^ DO
  380.             IF docTE <> NIL THEN
  381.                 TEDispose( docTE );
  382.         CloseWindow( window );
  383.         DisposPtr( Ptr( window ) );
  384.         gNumDocuments := gNumDocuments - 1;
  385.     END;
  386. END; { DoCloseWindow }
  387.  
  388.  
  389.  
  390. {$S Main}
  391. PROCEDURE AdjustTE( window : WindowPtr );
  392.  
  393. {    Scroll the TERec around to match up to the potentially updated scrollbar
  394.     values. This is really useful when the window resizes such that the
  395.     scrollbars become inactive and the TERec had been previously scrolled. }
  396.  
  397. VAR
  398.     value    : INTEGER;
  399.     
  400. BEGIN { AdjustTE }
  401.     WITH DocumentPeek( window )^ DO BEGIN
  402.         TEScroll( ( docTE^^.viewRect.left - docTE^^.destRect.left ) - GetCtlValue( docHScroll ),
  403.                 ( docTE^^.viewRect.top - docTE^^.destRect.top ) -
  404.                 GetCtlValue( docVScroll ) , docTE );
  405.     END; { with }
  406. END; { AdjustTE }
  407.  
  408.  
  409.  
  410. {$S Main}
  411. PROCEDURE AdjustHV( isVert : BOOLEAN; control : ControlHandle; 
  412.                     docTE : TEHandle; canRedraw : BOOLEAN );
  413.                     
  414. {Calculate the new control maximum value and current value, whether it is the horizontal or
  415. vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  416. vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  417. width to the width of the viewRect. The current values are set by comparing the offset between
  418. the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  419. calling ShowControl.}
  420.  
  421. {TEStyleSample-vertical max originally used line by line calculations-lineheight was a
  422. constant value so it was easy to figure out what the range should be and pin the value
  423. within range. Now we need to use max and min values in pixels rather than in nlines}
  424.  
  425. VAR
  426.     value, max             : INTEGER;
  427.     oldValue, oldMax    : INTEGER;
  428.     
  429. BEGIN { AdjustHV }
  430.     oldValue := GetCtlValue( control );
  431.     oldMax := GetCtlMax( control );
  432.     IF isVert THEN BEGIN
  433.         { new for TEStyleSample }
  434.         max := ( TEGetHeight( docTE^^.nLines, 0, docTE ) ) - 
  435.                             ( docTE^^.viewRect.bottom - docTE^^.viewRect.top );
  436.         
  437.     END ELSE
  438.         max := kMaxDocWidth - (docTE^^.viewRect.right - docTE^^.viewRect.left );
  439.     
  440.     IF max < 0 THEN
  441.         max := 0;            { check for negative values }
  442.     SetCtlMax( control, max );
  443.     IF isVert THEN
  444.         value := docTE^^.viewRect.top - docTE^^.destRect.top 
  445.     ELSE
  446.         value := docTE^^.viewRect.left - docTE^^.destRect.left;
  447.     IF value < 0 THEN
  448.         value := 0
  449.     ELSE IF value > max THEN
  450.         value := max;        { pin the value to within range }
  451.     SetCtlValue( control, value );
  452.     IF canRedraw & ( ( max <> oldMax ) | ( value <> oldValue ) ) THEN
  453.         ShowControl( control );            { check to see if the control can be re-drawn }
  454. END; { AdjustHV }
  455.  
  456.  
  457.  
  458. {$S Main}
  459. PROCEDURE AdjustScrollValues( window : WindowPtr; canRedraw : BOOLEAN );
  460.  
  461. {    Simply call the common adjust routine for the vertical and horizontal scrollbars. }
  462.  
  463. BEGIN { AdjustScrollValues }
  464.     WITH DocumentPeek( window )^ DO BEGIN
  465.         AdjustHV( TRUE, docVScroll, docTE, canRedraw );
  466.         AdjustHV( FALSE, docHScroll, docTE, canRedraw );
  467.     END; { with }
  468. END; { AdjustScrollValues }
  469.  
  470.  
  471.  
  472. {$S Main}
  473. PROCEDURE AdjustScrollSizes( window : WindowPtr );
  474.  
  475. {    Re-calculate the position and size of the viewRect and the scrollbars.
  476.      kScrollTweek compensates for off-by-one requirements of the scrollbars
  477.     to have borders coincide with the growbox. }
  478.  
  479. VAR
  480.     teRect    : Rect;
  481.  
  482. BEGIN { AdjustScrollSizes }
  483.     GetTERect( window, teRect ); {start with teRect}
  484.     WITH DocumentPeek( window )^, window^.portRect DO BEGIN
  485.         docTE^^.viewRect := teRect;
  486.         
  487.         { AdjustViewRect(docTE) was removed--no longer needed }
  488.         
  489.         MoveControl( docVScroll, right - kScrollbarAdjust, -1 );
  490.         SizeControl( docVScroll, kScrollbarWidth, ( bottom - top ) -
  491.                         ( kScrollbarAdjust - kScrollTweek ) );
  492.         MoveControl( docHScroll, -1, bottom - kScrollbarAdjust );
  493.         SizeControl( docHScroll, ( right - left ) - ( kScrollbarAdjust -
  494.                         kScrollTweek ), kScrollbarWidth );
  495.     END; { with }
  496. END; { AdjustScrollSizes }
  497.  
  498.  
  499.  
  500. {$S Main}
  501. PROCEDURE AdjustScrollbars( window : WindowPtr; needsResize : BOOLEAN );
  502.  
  503. {    Turn off the controls by jamming a zero into their contrlVis fields 
  504.     (HideControl erases them and we don't want that). If the controls are to 
  505.     be resized as well, call the procedure to do that, then call the procedure 
  506.     to adjust the maximum and current values. Finally re-enable the controls
  507.     by jamming a $FF in their contrlVis fields. }
  508.  
  509. VAR
  510.     oldMax, oldVal    : INTEGER;
  511.  
  512. BEGIN { AdjustScrollbars }
  513.     WITH DocumentPeek( window )^ DO BEGIN
  514.         docVScroll^^.contrlVis := kControlInvisible; { turn them off }
  515.         docHScroll^^.contrlVis := kControlInvisible;
  516.         IF needsResize THEN                            { move and size if needed }
  517.             AdjustScrollSizes( window );
  518.         AdjustScrollValues( window, NOT needsResize ); { fool with max and current value }
  519.         { Now, restore visibility in case we never had to ShowControl during adjustment }
  520.         docVScroll^^.contrlVis := kControlVisible; { turn them on }
  521.         docHScroll^^.contrlVis := kControlVisible;
  522.     END;
  523. END; { AdjustScrollbars }
  524.  
  525.  
  526.  
  527. {$S Main}
  528. {$PUSH} {$Z+}
  529. PROCEDURE PascalClikLoop;
  530.  
  531. {    Gets called from our assembly language routine, AsmClikLoop, which is in
  532.      turn called by the TEClick toolbox routine. Saves the windows clip region,
  533.      sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  534.      amount, then restores the clip region. }
  535.  
  536. VAR
  537.     window : WindowPtr;
  538.     region : RgnHandle;
  539.  
  540. BEGIN { PascalClikLoop }
  541.     window := FrontWindow;
  542.     region := NewRgn;
  543.     GetClip( region ); { save the old clip }
  544.     ClipRect( window^.portRect ); { set the new clip }
  545.     AdjustScrollValues( window, TRUE ); { pass TRUE for canRedraw }
  546.     SetClip( region ); { restore the old clip }
  547.     DisposeRgn( region );
  548. END; { PascalClikLoop }
  549. {$POP}
  550.  
  551.  
  552.  
  553. {$S Main}
  554. {$PUSH} {$Z+}
  555. FUNCTION GetOldClikLoop : ProcPtr;
  556.  
  557. {    Gets called from our assembly language routine, AsmClikLoop, which is in
  558.     turn called by the TEClick toolbox routine. It returns the address of the
  559.     default clikLoop routine that was put into the TERec by TEAutoView to
  560.     AsmClikLoop so that it can call it. }
  561.  
  562. BEGIN { GetOldClikLoop }
  563.     GetOldClikLoop := DocumentPeek( FrontWindow )^.docClik;
  564. END; { GetOldClikLoop }
  565. {$POP}
  566.  
  567.  
  568.  
  569. PROCEDURE AsmClikLoop; EXTERNAL;
  570.  
  571. {    A reference to our assembly language routine that gets attached to the clikLoop
  572.     field of our TE record. }
  573.  
  574.  
  575.  
  576. {$S Main}
  577. PROCEDURE DoNew;
  578.  
  579. {    Create a new document and window. }
  580.  
  581. {Minor changes from TESample--TEStylNew instead of TENew-makes certain fields in
  582. the edit record (lineHeight, txFont, and txFace) have value of -1 and alloctes new
  583. tables to hold style information}
  584.  
  585. VAR
  586.     good, ignore        : BOOLEAN;
  587.     storage                : Ptr;
  588.     window                : WindowPtr;
  589.     destRect, viewRect    : Rect;
  590.  
  591.  
  592. BEGIN { DoNew }
  593.     storage := NewPtr( SIZEOF( DocumentRecord ) );
  594.     IF storage <> NIL THEN BEGIN
  595.         window := GetNewWindow( rDocWindow, storage, WindowPtr( -1 ) );
  596.         IF window <> NIL THEN BEGIN
  597.             gNumDocuments := gNumDocuments + 1;
  598.             good := FALSE;
  599.             SetPort( window );
  600.             WITH window^, DocumentPeek( window )^ DO BEGIN
  601.                 GetTERect( window, viewRect );
  602.                 destRect := viewRect;
  603.                 destRect.right := destRect.left + kMaxDocWidth;
  604.                 docTE := TEStylNew( destRect, viewRect );
  605.                 { Use TEStylNew instead of TENew to initialize TERec correctly }
  606.                 IF docTE <> NIL THEN BEGIN
  607.                     good := TRUE;                {if TENew succeeded, we have a good document}
  608.                     TEAutoView(TRUE, docTE);
  609.                     docClik := docTE^^.clikLoop;
  610.                     docTE^^.clikLoop := @AsmClikLoop;
  611.                 END;
  612.                 IF good THEN BEGIN
  613.                     docVScroll := GetNewControl( rVScroll, window );
  614.                     good := ( docVScroll <> NIL );
  615.                 END; { if }
  616.                 IF good THEN BEGIN
  617.                     docHScroll := GetNewControl( rHScroll, window );
  618.                     good := ( docHScroll <> NIL );
  619.                 END; { if }
  620.                 IF good THEN BEGIN
  621.                     AdjustScrollValues( window, FALSE );
  622.                     ShowWindow( window ); { if the document is good, make the window visible }
  623.                 END ELSE BEGIN
  624.                     ignore := DoCloseWindow( window ); { otherwise regret we ever created it... }
  625.                     AlertUser( eNoWindow ); { and tell user }
  626.                 END { if }
  627.             END; { with }
  628.         END ELSE
  629.             DisposPtr( storage ); { get rid of the storage if it is never used }
  630.     END; { if }
  631. END; { DoNew }
  632.  
  633.  
  634.  
  635. {$S Main}
  636. PROCEDURE BigBadError( error : INTEGER );
  637. BEGIN
  638.     AlertUser( error );
  639.     ExitToShell;
  640. END;
  641.  
  642.  
  643.  
  644. {$S Initialize}
  645. PROCEDURE Initialize;
  646.  
  647. {    Set up the whole world, including global variables, Toolbox managers,
  648.      menus, and a single blank document.}
  649.     
  650. {If an error is detected, instead of merely doing an ExitToShell,
  651.  which leaves the user without much to go on, we call AlertUser, which puts
  652.  up a simple alert that just says an error occurred and then calls ExitToShell.
  653.  Since there is no other cleanup needed at this point if an error is detected,
  654.  this form of error- handling is acceptable. If more sophisticated error recovery
  655.  is needed, an exception mechanism, such as is provided by Signals, can be used.}
  656.  
  657.  
  658. VAR
  659.     menuBar                : Handle;
  660.     total, contig        : LongInt;
  661.     ignoreResult        : BOOLEAN;
  662.     event                : EventRecord;
  663.     count, ignoreError    : INTEGER;
  664.     
  665.     PROCEDURE BigBadError( error : INTEGER );
  666.     BEGIN
  667.         AlertUser( error );
  668.         ExitToShell;
  669.     END;
  670.  
  671. BEGIN { Initialize }
  672.     gInBackground := FALSE;
  673.  
  674.     InitGraf(@thePort);
  675.     InitFonts;
  676.     InitWindows;
  677.     InitMenus;
  678.     TEInit;
  679.     InitDialogs(NIL);
  680.     InitCursor;
  681.  
  682.     FOR count := 1 TO 3 DO
  683.         ignoreResult := EventAvail(everyEvent, event);
  684.     ignoreError := SysEnvirons(kSysEnvironsVersion, gMac);
  685.     IF gMac.machineType < 0 THEN BigBadError(eWrongMachine);
  686.     gHasWaitNextEvent := TrapAvailable(_WaitNextEvent, ToolTrap);
  687.  
  688.     
  689.     IF ORD( GetApplLimit ) - ORD( ApplicZone ) < kMinHeap THEN
  690.         BigBadError( eSmallSize );
  691.     PurgeSpace( total, contig );
  692.     IF total < kMinSpace THEN
  693.         IF UnloadScrap <> noErr THEN
  694.             BigBadError( eNoMemory )
  695.         ELSE BEGIN
  696.             PurgeSpace( total, contig );
  697.             IF total < kMinSpace THEN
  698.                 BigBadError( eNoMemory );
  699.         END; { if }
  700.  
  701.     menuBar := GetNewMBar( rMenuBar ); { read menus into menu bar }
  702.     IF menuBar = NIL THEN
  703.         BigBadError( eNoMemory );
  704.     SetMenuBar( menuBar ); { install menus }
  705.     DisposHandle( menuBar );
  706.     AddResMenu( GetMHandle( mApple ), 'DRVR' );    { add DA names to Apple menu }
  707.     AddResMenu( GetMHandle( mFont ),'FONT' ); { add Font names to Font Menu }
  708.     DrawMenuBar;
  709.     gNumDocuments := 0;
  710.  
  711.     { do other initialization here }
  712.     { set up printer stuff-this will allow the default pageSetup parameters to be used, so if
  713.       the used decides to print with out using pageSetup everything will be okay }
  714.       
  715.     gPrinterRecord := THPrint( NewHandle( SizeOF( TPrint ) ) ); {allocate a print record}
  716.     IF gPrinterRecord <> NIL THEN BEGIN {if we're successful then setup the default settings}
  717.         PrOpen; {open the record }
  718.         PrintDefault( gPrinterRecord ); { load in default settings }
  719.         PrClose; { close it up }
  720.     END; { if }
  721.  
  722.     DoNew; { create a single empty document }
  723. END; {Initialize}
  724.  
  725.  
  726.  
  727. {$S Main}    
  728. PROCEDURE PrintText( hTE : TEHandle );
  729.  
  730. {    Prints the edit record. Opens a printer port, calculates the numbers of lines
  731.     per page (it may be different for each page depending on the the text styles) and
  732.     then calls TEUpdate for the page, scroll a page and TEUpdate, etc. }
  733.  
  734. CONST
  735.     Margins                = 20;         { page margins }
  736.     
  737. VAR
  738.     totalLines            : INTEGER;    { number of lines in text }
  739.     rView                : Rect;        { viewRect for TERect }
  740.     oldPort                : grafPtr;    { hold original grafPtr }
  741.     oldView                : Rect;        { hold original viewRect }
  742.     oldDest                : Rect;        { hold original destRect }
  743.     totalHeight            : INTEGER;    { lineHeight for TERec }
  744.     currentLine            : INTEGER;    { what line are we on }
  745.     scrollAmount        : INTEGER;    { how much we scroll by }
  746.     zeroRect            : Rect;        { 0,0,0,0 rect used in clipRect }
  747.     
  748.     thePrinterStatus     : TPrStatus; { printer status }
  749.     openPrintManager    : BOOLEAN;    { flag if print manager can be opened okay }
  750.     abort                : BOOLEAN;    { flag if cmd-period is hit to exit routine }
  751.     viewHeight             : INTEGER;    { temp that has the viewRect height+1 to test conditions }
  752.  
  753.     
  754. BEGIN { PrintText }
  755.     OpenPrintManager := FALSE; {printer not open yet}
  756.     IF gPrinterRecord <> NIL THEN BEGIN { do we have a legitimate record?}
  757.         PrOpen; {open mr. print record if okay}
  758.         IF PrJobDialog( gPrinterRecord ) THEN BEGIN {bring up job dialog}
  759.             GetPort( oldPort ); { save the old stuff to restore later }
  760.             oldView := hTE^^.viewRect; 
  761.             oldDest := hTE^^.destRect;
  762.             gPrinterPort := PrOpenDoc( gPrinterRecord, NIL, NIL );
  763.             OpenPrintManager := ( PrError = noErr );
  764.         END; { if }
  765.     END; { if }
  766.  
  767.     IF OpenPrintManager THEN BEGIN
  768.         SetPort( grafPtr( gPrinterPort ) ); { printer port is now the current port }
  769.         SetRect( zeroRect, 0, 0, 0, 0 );
  770.  
  771.         rView := gPrinterRecord^^.PrInfo.rPage; { get the size of the page rectangle }
  772.         InsetRect( rView, Margins, Margins );  { adjust it for the margins }
  773.         hTE^^.inPort := GrafPtr( gPrinterPort ); { force TE to look at the printer port }
  774.         hTE^^.destRect := rView;
  775.         hTE^^.viewRect := rView; { set new view and dest rects to the TERec }
  776.         TECalText( hTE ); { recalculate our lineStarts array with the new rects }
  777.         totalLines := hTE^^.nLines; { get the number of lines in the newly sized TERec }
  778.         totalHeight := TEGetHeight( totalLines, 0, hTE );
  779.         hTE^^.destRect.bottom := hTE^^.destRect.top + totalHeight; { how tall our destRect is }
  780.         
  781.         abort := FALSE;
  782.         currentLine := 1; { TextEdit sez that TEGetHeight is 1 not 0 based }
  783.         
  784.         WHILE ( NOT ( abort ) AND ( currentLine <= totalLines ) ) DO BEGIN
  785.             PrOpenPage( gPrinterPort, NIL );
  786.             scrollAmount := 0;
  787.             ClipRect( gPrinterRecord^^.PrInfo.rPage ); { Open clipping so text will be drawn }
  788.             
  789.             viewHeight := hTE^^.viewRect.bottom - hTE^^.viewRect.top + 1;
  790.  
  791.             { figure out how many lines there are per page }
  792.             WHILE ((( scrollAmount + TEGetHeight( currentLine, currentLine, hTE ) ) <= viewHeight )
  793.                 AND ( currentLine <= totalLines ) )  DO BEGIN
  794.                 scrollAmount := scrollAmount + TEGetHeight( currentLine, currentLine, hTE );
  795.                 currentLine := currentLine + 1;
  796.             END; { while }
  797.             
  798.             hTE^^.viewRect.bottom := scrollAmount + Margins; { Add margins since top has a margin }
  799.             TEDeactivate( hTE ); { Deactive the edit record so we don't print the cursor or selection range }
  800.             TEUpdate( hTE^^.viewRect, hTE ); { print the page }
  801.             ClipRect( zeroRect ); { Close clipping so that TEScroll doesn't redraw the text }
  802.             TEScroll( 0, -scrollAmount, hTE ); { scroll the page so we can print the next one }
  803.             hTE^^.viewRect.bottom := rView.bottom; { reset bottom to full page }
  804.     
  805.             IF prError = iPrAbort THEN 
  806.                 abort := TRUE;
  807.             PrClosePage( gPrinterPort ); { close everything up }
  808.         END; { while }
  809.  
  810.         PrCloseDoc( gPrinterPort );
  811.         IF ( gPrinterRecord^^.prJob.bJDocLoop = bSpoolLoop ) AND ( PrError = noErr ) THEN
  812.             PrPicFile( gPrinterRecord, NIL, NIL, NIL, thePrinterStatus );
  813.         PrClose;
  814.         SetPort( oldPort );
  815.         hTE^^.inPort := oldPort;
  816.         hTE^^.viewRect := oldView; { restore the old stuff when we are done }
  817.         hTE^^.destRect := oldDest;
  818.         TEUpdate( hTE^^.viewRect, hTE ); { update everything after resetting the port }
  819.     END; { if }
  820. END; { PrintText }
  821.  
  822.  
  823.  
  824. {$S Main}
  825. PROCEDURE Terminate;
  826.  
  827. {    Clean up the application and exit. We close all of the windows so that
  828.     they can update their documents, if any. }
  829.  
  830. VAR
  831.     aWindow    : WindowPtr;
  832.     closed    : BOOLEAN;
  833.  
  834. BEGIN { Terminate }
  835.     closed := TRUE;
  836.     REPEAT
  837.         aWindow := FrontWindow; { get the current front window }
  838.         IF aWindow <> NIL THEN
  839.             closed := DoCloseWindow( aWindow );    { close this window }
  840.     UNTIL ( NOT closed ) | ( aWindow = NIL ); { do all windows }
  841.     IF closed THEN
  842.         ExitToShell; { exit if no cancellation }
  843. END; { Terminate }
  844.  
  845.  
  846.  
  847. {$S Main}
  848. PROCEDURE AdjustMenus;
  849.  
  850. VAR
  851.     window            : WindowPtr;
  852.     menu            : MenuHandle;
  853.     offset            : LONGINT;
  854.     undo            : BOOLEAN;    { flag to enable/disable undo command }
  855.     cutCopyClear    : BOOLEAN;    { flag to enable/disable editing commands }
  856.     paste            : BOOLEAN;    
  857.     selectAll        : BOOLEAN;    
  858.     
  859.     doPrint            : BOOLEAN;    { flag to enable/disable printing item }
  860.     
  861.     te                : TEHandle;    { local te handle }
  862.     mode            : INTEGER;    { current style }
  863.     
  864.  
  865. BEGIN
  866.     window := FrontWindow;
  867.  
  868.     menu := GetMHandle( mFile );
  869.     IF gNumDocuments < kMaxOpenDocuments THEN
  870.         EnableItem( menu, iNew ) { New is enabled when we can open more documents }
  871.     ELSE
  872.         DisableItem( menu, iNew );
  873.     
  874.     IF window <> NIL THEN { Close is enabled when there is a window to close }
  875.         EnableItem( menu, iClose )
  876.     ELSE
  877.         DisableItem( menu, iClose );
  878.  
  879.     menu := GetMHandle( mEdit );
  880.     undo := FALSE;
  881.     cutCopyClear := FALSE;
  882.     paste := FALSE;
  883.     selectAll := FALSE;
  884.     doPrint := FALSE;
  885.     
  886.     IF IsDAWindow( window ) THEN BEGIN
  887.         undo := TRUE; { all editing is enabled for DA windows }
  888.         cutCopyClear := TRUE;
  889.         paste := TRUE;
  890.         selectAll := TRUE;
  891.     END ELSE IF IsAppWindow( window ) THEN BEGIN
  892.         WITH DocumentPeek( window )^.docTE^^ DO
  893.             IF selStart < selEnd THEN BEGIN
  894.                 cutCopyClear := TRUE;
  895.             END; { if }
  896.                 { Cut, Copy, and Clear is enabled for app. windows with selections }
  897.         IF GetScrap( NIL, 'TEXT', offset ) > 0 THEN
  898.             paste := TRUE; { Paste is enabled for app. windows }
  899.         
  900.         selectAll := TRUE;
  901.         doPrint := TRUE;
  902.             
  903.         mode := doFace;
  904.         menu := GetMHandle( mStyle );
  905.         IF TEContinuousStyle( mode, gTxStyle, DocumentPeek( window )^.docTE ) THEN BEGIN
  906.             CheckItem( menu, iPlain, gTxStyle.tsface = [] );
  907.             CheckItem( menu, iBold, bold in gTxStyle.tsFace );
  908.             CheckItem( menu, iItalic, italic in gTxStyle.tsFace );
  909.             CheckItem( menu, iUnderline, underline in gTxStyle.tsFace );
  910.             CheckItem( menu, iOutline, outline in gTxStyle.tsFace );
  911.             CheckItem( menu, iShadow, shadow in gTxStyle.tsFace );
  912.         END ELSE BEGIN
  913.             CheckItem( menu, iPlain, FALSE );
  914.             CheckItem( menu, iBold, FALSE );
  915.             CheckItem( menu, iItalic, FALSE );
  916.             CheckItem( menu, iUnderline, FALSE );
  917.             CheckItem( menu, iOutline, FALSE );
  918.             CheckItem( menu, iShadow, FALSE );
  919.         END; { if }
  920.  
  921.     END; { if }
  922.     menu := GetMHandle( mEdit );
  923.     
  924.     IF undo THEN
  925.         EnableItem( menu, iUndo )
  926.     ELSE
  927.         DisableItem( menu, iUndo );
  928.     
  929.     IF cutCopyClear THEN BEGIN
  930.         EnableItem( menu, iCut );
  931.         EnableItem( menu, iCopy );
  932.         EnableItem( menu, iClear );
  933.     END ELSE BEGIN
  934.         DisableItem( menu, iCut );
  935.         DisableItem( menu, iCopy );
  936.         DisableItem( menu, iClear );
  937.     END; { if }
  938.     
  939.     
  940.     IF paste THEN
  941.         EnableItem( menu, iPaste )
  942.     ELSE
  943.         DisableItem( menu, iPaste );
  944.         
  945.     IF selectAll THEN 
  946.         EnableItem( menu, iSelectAll )
  947.     ELSE
  948.         DisableItem( menu, iSelectAll );
  949.  
  950.         
  951.     menu := GetMHandle( mFile );
  952.     IF doPrint THEN BEGIN
  953.         EnableItem( menu, iPageSetup );
  954.         EnableItem( menu, iPrint );
  955.     END ELSE BEGIN
  956.         DisableItem( menu, iPageSetup );
  957.         DisableItem( menu, iPrint );
  958.     END; { if }
  959.         
  960.                 
  961. END; { AdjustMenus }
  962.  
  963.  
  964.  
  965. {$S Main}
  966. PROCEDURE DoMenuCommand( menuResult : LONGINT );
  967.  
  968. {    This is called when an item is chosen from the menu bar (after calling
  969.     MenuSelect or MenuKey). It does the right thing for each command. }
  970.  
  971. VAR
  972.     menuID, menuItem        : INTEGER;
  973.     itemHit, daRefNum        : INTEGER;
  974.     daName                    : Str255;
  975.     
  976.     tempStr                    : Str255;
  977.     menu                    : MenuHandle;
  978.     anIntPtr                : ^INTEGER;
  979.     
  980.     ignoreResult, saveErr    : OSErr;
  981.     handledByDA                : BOOLEAN;
  982.     te                        : TEHandle;
  983.     window                    : WindowPtr;
  984.     ignore                    : BOOLEAN;
  985.     aHandle                    : Handle;
  986.     oldSize, newSize        : LONGINT;
  987.     total, contig            : LONGINT;
  988.  
  989.     
  990. BEGIN
  991.     window := FrontWindow;
  992.     menuID := HiWrd( menuResult ); { use built-ins (for efficiency)... }
  993.     menuItem := LoWrd( menuResult ); { to get menu item number and menu number }
  994.     te := DocumentPeek( window )^.docTE;
  995.                 
  996.     CASE menuID OF
  997.     
  998.         mApple:
  999.             CASE menuItem OF
  1000.                 iAbout:                {bring up alert for About}
  1001.                     itemHit := Alert(rAboutAlert, NIL);
  1002.                 OTHERWISE BEGIN        { all non-About items in this menu are DAs }
  1003.                     GetItem( GetMHandle( mApple ), menuItem, daName );
  1004.                     daRefNum := OpenDeskAcc( daName );
  1005.                 END; { otherwise }
  1006.             END; { case }
  1007.             
  1008.         mFile:
  1009.             CASE menuItem OF
  1010.                 iNew:
  1011.                     DoNew;
  1012.                 iClose:
  1013.                     ignore := DoCloseWindow( window ); { we don't care if cancelled }
  1014.                 iPageSetup: BEGIN
  1015.                     PrOpen;
  1016.                     IF PrError = noErr THEN
  1017.                         ignore := PrStlDialog( gPrinterRecord );
  1018.                     PrClose;
  1019.                 END; { iPageSetup }
  1020.                 iPrint:
  1021.                     PrintText( te );
  1022.                 iQuit:
  1023.                     Terminate;
  1024.             END; { case }
  1025.             
  1026.         mEdit: BEGIN                { call SystemEdit for DA editing & MultiFinder }
  1027.             IF NOT SystemEdit( menuItem -1 ) THEN BEGIN
  1028.                 CASE menuItem OF
  1029.                     
  1030.                     iCut: BEGIN        
  1031.                         IF ZeroScrap = noErr THEN BEGIN
  1032.                             PurgeSpace( total, contig );
  1033.                             IF ( te^^.selEnd - te^^.selStart ) + kTESlop > contig THEN
  1034.                                 AlertUser( eNoSpaceCut )
  1035.                             ELSE BEGIN
  1036.                                 TECut( te );
  1037.                             END; { if }
  1038.                         END; { if }
  1039.                     END; { iCut }
  1040.                     
  1041.                     iCopy: BEGIN
  1042.                         IF ZeroScrap = noErr THEN BEGIN
  1043.                             TECopy( te );
  1044.                         END; { if }
  1045.                     END; { iCopy }
  1046.                     
  1047.                     iPaste: BEGIN
  1048.                         IF TEGetScrapLen + ( te^^.teLength -
  1049.                             ( te^^.selEnd - te^^.selStart ) ) > kMaxTELength THEN
  1050.                             AlertUser( eExceedPaste )
  1051.                         ELSE BEGIN
  1052.                             aHandle := Handle( TEGetText( te ) );
  1053.                             oldSize := GetHandleSize( aHandle );
  1054.                             newSize := oldSize + TEGetScrapLen + kTESlop;
  1055.                             SetHandleSize( aHandle, newSize );
  1056.                             saveErr := MemError;
  1057.                             SetHandleSize( aHandle, oldSize );
  1058.                             IF saveErr <> noErr THEN
  1059.                                 AlertUser( eNoSpacePaste )
  1060.                             ELSE
  1061.                                 TEStylPaste( te );
  1062.                         END; { if }
  1063.                     END; { iPaste }
  1064.                     
  1065.                     iClear:
  1066.                         TEDelete( te );
  1067.                         
  1068.                     iSelectAll:
  1069.                         TESetSelect( 0, te^^.teLength, te );
  1070.                         
  1071.                 END; { case }
  1072.                 if menuItem <> iCopy then
  1073.                     AdjustScrollBars( window, FALSE );
  1074.             END; { if }
  1075.         END; { mEdit }
  1076.         
  1077.         mFont :
  1078.             BEGIN { mFont }
  1079.                 GetItem( GetMHandle( mFont ), menuItem, gFontName );
  1080.                 getFNum( gFontName, gFontID );
  1081.                 gTxStyle.tsFont := gFontID;
  1082.                 TESetStyle( doFont, gTxStyle, true, te );
  1083.                 AdjustScrollBars( window, FALSE );
  1084.             END; { mFont }
  1085.             
  1086.         mFontSize :
  1087.             BEGIN { mFontSize }
  1088.                 CASE menuItem OF
  1089.                     iNine        : gFontSize := 9;
  1090.                     iTen        : gFontSize := 10;
  1091.                     iTwelve        : gFontSize := 12;
  1092.                     iFourteen    : gFontSize := 14;
  1093.                     iEighteen    : gFontSize := 18;
  1094.                     iTwoFour    : gFontSize := 24;
  1095.                 END; { case }
  1096.                 gTxStyle.tsSize := gFontSize;
  1097.                 TESetStyle( doSize, gTxStyle, TRUE, te );
  1098.                 AdjustScrollBars( window, FALSE );
  1099.             END; { mFontSize }
  1100.             
  1101.         mStyle :
  1102.             BEGIN { mStyle }
  1103.                 WITH gTxStyle DO BEGIN
  1104.                     CASE menuItem OF
  1105.                         iPlain         : 
  1106.                             BEGIN
  1107.                                 anIntPtr := @gTxStyle.tsFace; { as per Tech Note #131 }
  1108.                                 anIntPtr^ := 0;
  1109.                                 tsFace := [];
  1110.                             END;
  1111.                         iBold         : tsFace := [bold];
  1112.                         iItalic     : tsFace := [italic];
  1113.                         iUnderline     : tsFace := [underline];
  1114.                         iOutline     : tsFace := [outline];
  1115.                         iShadow     : tsFace := [shadow];
  1116.                     END; { case }                
  1117.                     
  1118.                     IF menuItem <> 1 THEN
  1119.                         TESetStyle( doFace + doToggle, gTxStyle, TRUE, te )
  1120.                          { if we don't select plain then use doToggle }
  1121.                     ELSE
  1122.                         TESetStyle( doFace, gTxStyle, TRUE, te );
  1123.                         { TESetStyle has problems with plain and doToggle-has no effect!
  1124.                           so we need to special case it. }
  1125.                     AdjustScrollBars( window, FALSE );
  1126.                 END; { with }
  1127.             END; { mStyle }
  1128.                         
  1129.     END; { case }
  1130.     HiliteMenu( 0 ); { unhighlight what MenuSelect (or MenuKey) hilited }
  1131. END; { DoMenuCommand }
  1132.  
  1133.  
  1134.  
  1135. {$S Main}
  1136. PROCEDURE DrawWindow( window : WindowPtr );
  1137.  
  1138. {    Draw the contents of an application window. }
  1139.  
  1140. BEGIN { DrawWindow }
  1141.     SetPort( window );
  1142.     WITH window^ DO BEGIN
  1143.         EraseRect( portRect ); { as per TextEdit chapter of Inside Macintosh }
  1144.         DrawControls( window ); { this ordering makes for a better appearance }
  1145.         DrawGrowIcon( window );
  1146.         TEUpdate( portRect, DocumentPeek( window )^.docTE );
  1147.     END; { with }
  1148. END; { DrawWindow }
  1149.  
  1150.  
  1151.  
  1152. {$S Main}
  1153. FUNCTION GetSleep : LONGINT;
  1154.  
  1155. {    Calculate a sleep value for WaitNextEvent. This takes into account the things
  1156.      that DoIdle does with idle time. }
  1157.  
  1158. VAR
  1159.     sleep    : LONGINT;
  1160.     window    : WindowPtr;
  1161.  
  1162. BEGIN { GetSleep }
  1163.     sleep := MAXLONGINT; { default value for sleep }
  1164.     IF NOT gInBackground THEN BEGIN { if we are in front... }
  1165.         window := FrontWindow; { and the front window is ours... }
  1166.         IF IsAppWindow( window ) THEN BEGIN
  1167.             WITH DocumentPeek( window )^.docTE^^ DO
  1168.                 IF selStart = selEnd THEN { and the selection is an insertion point... }
  1169.                     sleep := GetCaretTime; { we need to blink the insertion point }
  1170.         END; { if }
  1171.     END; { if }
  1172.     GetSleep := sleep;
  1173. END; { GetSleep }
  1174.  
  1175.  
  1176.  
  1177. {$S Main}
  1178. PROCEDURE CommonAction( control : ControlHandle; VAR amount : INTEGER );
  1179.  
  1180. {    Common algorithm for setting the new value of a control. It returns the actual amount
  1181.     the value of the control changed. Note the pinning is done for the sake of returning
  1182.     the amount the control value changed. }
  1183.  
  1184. VAR
  1185.     value, max    : INTEGER;
  1186.     window        : WindowPtr;
  1187.  
  1188. BEGIN { CommonAction }
  1189.     value := GetCtlValue( control ); { get current value }
  1190.     max := GetCtlMax( control ); { and max value }
  1191.     amount := value - amount;
  1192.     IF amount < 0 THEN
  1193.         amount := 0
  1194.     ELSE IF amount > max THEN
  1195.         amount := max;
  1196.     SetCtlValue( control, amount );
  1197.     amount := value - amount; { calculate true change }
  1198. END; { CommonAction }
  1199.  
  1200.  
  1201.  
  1202. {$S Main}
  1203. PROCEDURE VActionProc( control : ControlHandle; part : INTEGER );
  1204.  
  1205. {    Determines how much to change the value of the vertical scrollbar by and how
  1206.     much to scroll the TE record. }
  1207.  
  1208. VAR
  1209.     amount    : INTEGER;
  1210.     window    : WindowPtr;
  1211.  
  1212. BEGIN { VActionProc }
  1213.     IF part <> 0 THEN BEGIN
  1214.         window := control^^.contrlOwner;
  1215.         WITH DocumentPeek( window )^, DocumentPeek( window )^.docTE^^ DO BEGIN
  1216.             CASE part OF
  1217.                 inUpButton, inDownButton :
  1218.                     amount := 24;
  1219.                 inPageUp, inPageDown :
  1220.                     amount := viewRect.bottom - viewRect.top; { one page }
  1221.             END; { case }
  1222.             IF ( part = inDownButton ) | ( part = inPageDown ) THEN
  1223.                 amount := -amount; { reverse direction }
  1224.             CommonAction( control, amount );
  1225.             IF amount <> 0 THEN
  1226.                 TEScroll( 0, amount, docTE );
  1227.         END; { with }
  1228.     END; { if }
  1229. END; { VActionProc }
  1230.  
  1231.  
  1232.  
  1233. {$S Main}
  1234. PROCEDURE HActionProc( control : ControlHandle; part : INTEGER );
  1235.  
  1236. {    Determines how much to change the value of the horizontal scrollbar by and how
  1237.     much to scroll the TE record. }
  1238.  
  1239. VAR
  1240.     amount    : INTEGER;
  1241.     window    : WindowPtr;
  1242.  
  1243. BEGIN { HActionProc }
  1244.     IF part <> 0 THEN BEGIN
  1245.         window := control^^.contrlOwner;
  1246.         WITH DocumentPeek( window )^, DocumentPeek( window )^.docTE^^ DO BEGIN
  1247.             CASE part OF
  1248.                 inUpButton, inDownButton :
  1249.                     amount := kButtonScroll; { a few pixels }
  1250.                 inPageUp, inPageDown :
  1251.                     amount := viewRect.right - viewRect.left; { a page }
  1252.             END; { case }
  1253.             IF ( part = inDownButton ) | ( part = inPageDown ) THEN
  1254.                 amount := -amount; { reverse direction }
  1255.             CommonAction( control, amount );
  1256.             IF amount <> 0 THEN
  1257.                 TEScroll( amount, 0, docTE );
  1258.         END; { with }
  1259.     END; { if }
  1260. END; { HActionProc }
  1261.  
  1262.  
  1263.  
  1264. {$S Main}
  1265. PROCEDURE DoIdle;
  1266.  
  1267. {    This is called whenever we get an null event or a mouse-moved event.
  1268.      It takes care of necessary periodic actions. For this program, it calls TEIdle. }
  1269.  
  1270. VAR
  1271.     window    : WindowPtr;
  1272.  
  1273. BEGIN { DoIdle }
  1274.     window := FrontWindow;
  1275.     IF IsAppWindow( window ) THEN
  1276.         TEIdle( DocumentPeek( window )^.docTE );
  1277. END; { DoIdle }
  1278.  
  1279.  
  1280.  
  1281. {$S Main}
  1282. PROCEDURE DoKeyDown( event : EventRecord );
  1283.  
  1284. {    This is called for any keyDown or autoKey events, except when the
  1285.     Command key is held down. It looks at the frontmost window to decide what
  1286.      to do with the key typed. }
  1287.  
  1288. VAR
  1289.     window    : WindowPtr;
  1290.     key        : CHAR;
  1291.     te        : TEHandle;
  1292.  
  1293. BEGIN
  1294.     window := FrontWindow;
  1295.     IF IsAppWindow( window ) THEN BEGIN
  1296.         te := DocumentPeek( window)^.docTE;
  1297.         key := CHR( BAnd( event.message, charCodeMask ) );
  1298.         IF ( key = CHR(kDelChar ) ) |     { don't count deletes }
  1299.             ( te^^.teLength - ( te^^.selEnd - te^^.selStart )
  1300.                             + 1 < kMaxTELength ) THEN BEGIN    { but check haven't gone past }
  1301.             TEKey( key, te );
  1302.             AdjustScrollbars( window, FALSE );
  1303.         END ELSE
  1304.             AlertUser( eExceedChar );
  1305.     END; { if }
  1306. END; { DoKeyDown }
  1307.  
  1308.  
  1309.  
  1310. {$S Main}
  1311. PROCEDURE DoContentClick( window : WindowPtr; event : EventRecord );
  1312.  
  1313. {    Called when a mouseDown occurs in the content of a window. }
  1314.  
  1315. VAR
  1316.     mouse        : Point;
  1317.     control        : ControlHandle;
  1318.     part, value    : INTEGER;
  1319.     shiftDown    : BOOLEAN;
  1320.     teRect        : Rect;
  1321.     
  1322. BEGIN { DoContentClick }
  1323.     IF IsAppWindow( window ) THEN BEGIN
  1324.         SetPort( window );
  1325.         mouse := event.where; { get the click position }
  1326.         GlobalToLocal( mouse ); { convert to local coordinates }
  1327.         
  1328.         GetTERect( window, teRect );
  1329.         IF PtInRect( mouse, teRect ) THEN BEGIN
  1330.             shiftDown := BAnd( event.modifiers, shiftKey ) <> 0; { extend if Shift is down }
  1331.             TEClick( mouse, shiftDown, DocumentPeek( window )^.docTE );
  1332.         END ELSE BEGIN
  1333.             part := FindControl( mouse, window, control );
  1334.             WITH DocumentPeek( window )^ DO
  1335.                 CASE part OF
  1336.                     0:;     { do nothing for viewRect case }
  1337.                     inThumb: BEGIN
  1338.                         value := GetCtlValue( control );
  1339.                         part := TrackControl( control, mouse, NIL );
  1340.                         IF part <> 0 THEN BEGIN
  1341.                             value := value - GetCtlValue( control );
  1342.                             IF value <> 0 THEN
  1343.                                 IF control = docVScroll THEN
  1344.                                     TEScroll( 0, value, docTE )
  1345.                                 ELSE
  1346.                                     TEScroll( value, 0, docTE );
  1347.                         END; { if }
  1348.                     END; { inThumb }
  1349.                     OTHERWISE    { must be page or button }
  1350.                         IF control = docVScroll THEN
  1351.                             value := TrackControl( control, mouse, @VActionProc )
  1352.                         ELSE
  1353.                             value := TrackControl( control, mouse, @HActionProc );
  1354.                 END; { case }
  1355.         END; { if }
  1356.     END; { if }
  1357. END; { DoContentClick }
  1358.  
  1359.  
  1360.  
  1361. {$S Main}
  1362. PROCEDURE ResizeWindow( window : WindowPtr );
  1363.  
  1364. {    Called when the window has been resized to fix up the controls and content }
  1365.  
  1366. BEGIN { ResizeWindow }
  1367.     WITH window^ DO BEGIN
  1368.         AdjustScrollbars( window, TRUE );
  1369.         AdjustTE( window );
  1370.         InvalRect( portRect );
  1371.     END;
  1372. END; { ResizeWindow }
  1373.  
  1374.  
  1375.  
  1376. {$S Main}
  1377. PROCEDURE GetLocalUpdateRgn( window : WindowPtr; localRgn : RgnHandle );
  1378.  
  1379. {    Returns the update region in local coordinates }
  1380.  
  1381. BEGIN { GetLocalUpdateRgn }
  1382.     CopyRgn( WindowPeek( window )^.updateRgn, localRgn ); { save old update region }
  1383.     WITH window^.portBits.bounds DO
  1384.         OffsetRgn( localRgn, left, top ); { convert to local coords }
  1385. END; { GetLocalUpdateRgn }
  1386.  
  1387.  
  1388.  
  1389. {$S Main}
  1390. PROCEDURE DoGrowWindow( window : WindowPtr; event : EventRecord );
  1391.  
  1392. {    Called when a mouseDown occurs in the grow box of an active window. In
  1393.      order to eliminate any 'flicker', we want to invalidate only what is
  1394.      necessary. Since ResizeWindow invalidates the whole portRect, we save
  1395.      the old TE viewRect, intersect it with the new TE viewRect, and
  1396.      remove the result from the update region. However, we must make sure
  1397.      that any old update region that might have been around gets put back. }
  1398.  
  1399. VAR
  1400.     growResult        : LONGINT;
  1401.     tempRect        : Rect;
  1402.     tempRgn            : RgnHandle;
  1403.     ignoreResult    : BOOLEAN;
  1404.  
  1405. BEGIN { DoGrowWindow }
  1406.     WITH screenBits.bounds DO
  1407.         SetRect( tempRect, kMinDocDim, kMinDocDim, right, bottom ); { set up limiting values }
  1408.     growResult := GrowWindow( window, event.where, tempRect );
  1409.     IF growResult <> 0 THEN  { see if changed size }
  1410.         WITH DocumentPeek( window )^, window^ DO BEGIN
  1411.             tempRect := docTE^^.viewRect; { save old text box }
  1412.             tempRgn := NewRgn;
  1413.             GetLocalUpdateRgn( window, tempRgn ); { get localized update region }
  1414.             SizeWindow( window, LoWrd( growResult ), HiWrd( growResult ), TRUE );
  1415.             ResizeWindow( window );
  1416.             ignoreResult := SectRect( tempRect, docTE^^.viewRect, tempRect ); { find what stayed same }
  1417.             ValidRect( tempRect ); { take it out of update }
  1418.             InvalRgn( tempRgn ); { put back any prior update }
  1419.             DisposeRgn( tempRgn );
  1420.         END; { with }
  1421. END; { DoGrowWindow }
  1422.  
  1423.  
  1424.  
  1425. {$S Main}
  1426. PROCEDURE DoZoomWindow( window : WindowPtr; part : INTEGER );
  1427.  
  1428. {    Called when a mouseClick occurs in the zoom box of an active window.
  1429.     Everything has to get re-drawn here, so we don't mind that
  1430.     ResizeWindow invalidates the whole portRect. }
  1431.  
  1432. BEGIN { DoZoomWindow }
  1433.     WITH window^ DO BEGIN
  1434.         EraseRect( portRect );
  1435.         ZoomWindow( window, part, ( window = FrontWindow ) );
  1436.         ResizeWindow( window );
  1437.     END; { with }
  1438. END; { DoZoomWindow }
  1439.  
  1440.  
  1441.  
  1442. {$S Main}
  1443. PROCEDURE DoUpdate( window : WindowPtr );
  1444.  
  1445. {    This is called when an update event is received for a window.
  1446.      It calls DrawWindow to draw the contents of an application window,
  1447.      but only if the visRgn is non-empty; for efficiency reasons,
  1448.      not because it is required. }
  1449.  
  1450. BEGIN { DoUpdate }
  1451.     IF IsAppWindow( window ) THEN BEGIN
  1452.         BeginUpdate( window ); { this sets up the visRgn }
  1453.         IF NOT EmptyRgn( window^.visRgn ) THEN    { draw if updating needs to be done }
  1454.             DrawWindow( window );
  1455.         EndUpdate( window );
  1456.     END; { if }
  1457. END; { DoUpdate }
  1458.  
  1459.  
  1460.  
  1461. {$S Main}
  1462. PROCEDURE DoActivate( window : WindowPtr; becomingActive : BOOLEAN );
  1463.  
  1464. {    This is called when a window is activated or deactivated. }
  1465.  
  1466. VAR
  1467.     tempRgn, clipRgn    : RgnHandle;
  1468.     growRect            : Rect;
  1469.  
  1470. BEGIN { DoActivate }
  1471.     IF IsAppWindow( window ) THEN
  1472.         WITH DocumentPeek( window )^ DO
  1473.             IF becomingActive THEN BEGIN
  1474.                 { since we don’t want TEActivate to draw a selection in an area where
  1475.                   we’re going to erase and redraw, we’ll clip out the update region
  1476.                   before calling it. }
  1477.                 tempRgn := NewRgn;
  1478.                 clipRgn := NewRgn;
  1479.                 GetLocalUpdateRgn( window, tempRgn ); { get localized update region }
  1480.                 GetClip( clipRgn );
  1481.                 DiffRgn( clipRgn, tempRgn, tempRgn ); { subtract updateRgn from clipRgn }
  1482.                 SetClip( tempRgn );
  1483.                 TEActivate( docTE ); { let TE do its thing }
  1484.                 SetClip( clipRgn ); { restore the full-blown clipRgn }
  1485.                 DisposeRgn( tempRgn );
  1486.                 DisposeRgn( clipRgn );
  1487.  
  1488.                 {the controls need to be redrawn on activation:}
  1489.                 docVScroll^^.contrlVis := kControlVisible;
  1490.                 docHScroll^^.contrlVis := kControlVisible;
  1491.                 InvalRect( docVScroll^^.contrlRect );
  1492.                 InvalRect( docHScroll^^.contrlRect );
  1493.                 { the growbox needs to be redrawn on activation: }
  1494.                 growRect := window^.portRect;
  1495.                 WITH growRect DO BEGIN
  1496.                     top := bottom - kScrollbarAdjust; { adjust for the scrollbars }
  1497.                     left := right - kScrollbarAdjust;
  1498.                 END; { with }
  1499.                 InvalRect( growRect );
  1500.             END ELSE BEGIN
  1501.                 TEDeactivate( docTE );
  1502.                 { the controls should be hidden immediately on deactivation: }
  1503.                 HideControl( docVScroll );
  1504.                 HideControl( docHScroll );
  1505.                 { the growbox should be changed immediately on deactivation: }
  1506.                 DrawGrowIcon( window );
  1507.             END; { if }
  1508. END; { DoActivate }
  1509.  
  1510.  
  1511.  
  1512. {$S Main}
  1513. PROCEDURE GetGlobalMouse(VAR mouse: Point);
  1514.  
  1515. {Get the global coordinates of the mouse. When you call OSEventAvail
  1516.  it will return either a pending event or a null event. In either case,
  1517.  the where field of the event record will contain the current position
  1518.  of the mouse in global coordinates and the modifiers field will reflect
  1519.  the current state of the modifiers. Another way to get the global
  1520.  coordinates is to call GetMouse and LocalToGlobal, but that requires
  1521.  being sure that thePort is set to a valid port.}
  1522.  
  1523. VAR
  1524.     event    : EventRecord;
  1525.     
  1526. BEGIN
  1527.     IF OSEventAvail(kNoEvents, event) THEN;    {we aren't interested in any events}
  1528.     mouse := event.where;                    {just the mouse position}
  1529. END;
  1530.  
  1531.  
  1532.  
  1533. {$S Main}
  1534. PROCEDURE AdjustCursor( mouse : Point; region : RgnHandle );
  1535.  
  1536. { Change the cursor's shape, depending on its position. This also calculates a region
  1537.  that includes the cursor for WaitNextEvent. }
  1538.  
  1539. VAR
  1540.     window        : WindowPtr;
  1541.     arrowRgn    : RgnHandle;
  1542.     iBeamRgn    : RgnHandle;
  1543.     iBeamRect    : Rect;
  1544.  
  1545. BEGIN { AdjustCursor }
  1546.     window := FrontWindow; { we only adjust the cursor when we are in front }
  1547.     IF ( NOT gInBackground ) AND ( NOT IsDAWindow( window ) ) THEN BEGIN
  1548.         { calculate regions for different cursor shapes}
  1549.         arrowRgn := NewRgn;
  1550.         iBeamRgn := NewRgn;
  1551.  
  1552.         { start with a big, big rectangular region }
  1553.         SetRectRgn( arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos );
  1554.  
  1555.         { calculate iBeamRgn }
  1556.         IF IsAppWindow( window ) THEN BEGIN
  1557.             iBeamRect := DocumentPeek( window )^.docTE^^.viewRect;
  1558.             SetPort( window ); { make a global version of the viewRect }
  1559.             WITH iBeamRect DO BEGIN
  1560.                 LocalToGlobal( topLeft );
  1561.                 LocalToGlobal( botRight );
  1562.             END; { with }
  1563.             RectRgn( iBeamRgn, iBeamRect );
  1564.             WITH window^.portBits.bounds DO
  1565.                 SetOrigin( -left, -top );
  1566.             SectRgn( iBeamRgn, window^.visRgn, iBeamRgn );
  1567.             SetOrigin( 0, 0 );
  1568.         END; { if }
  1569.  
  1570.         { subtract other regions from arrowRgn }
  1571.         DiffRgn( arrowRgn, iBeamRgn, arrowRgn );
  1572.         
  1573.         {change the cursor and the region parameter}
  1574.         IF PtInRgn( mouse, iBeamRgn ) THEN BEGIN
  1575.             SetCursor( GetCursor( iBeamCursor )^^ );
  1576.             CopyRgn( iBeamRgn, region );
  1577.         END ELSE BEGIN
  1578.             SetCursor( arrow );
  1579.             CopyRgn( arrowRgn, region );
  1580.         END; { if }
  1581.  
  1582.         { get rid of our local regions }
  1583.         DisposeRgn( arrowRgn );
  1584.         DisposeRgn( iBeamRgn );
  1585.     END; { if }
  1586. END; { AdjustCursor }
  1587.  
  1588.  
  1589.  
  1590. {$S Main}
  1591. PROCEDURE DoEvent( event : EventRecord );
  1592.  
  1593. {    Do the right thing for an event. Determine what kind of event it is, and call
  1594.      the appropriate routines. }
  1595.  
  1596. VAR
  1597.     part, err    : INTEGER;
  1598.     window        : WindowPtr;
  1599.     key            : CHAR;
  1600.     ignore        : BOOLEAN;
  1601.     aPoint        : Point;
  1602.  
  1603. BEGIN { DoEvent }
  1604.     CASE event.what OF
  1605.         nullEvent:
  1606.             DoIdle;
  1607.         mouseDown: BEGIN
  1608.             part := FindWindow( event.where, window );
  1609.             CASE part OF
  1610.                 
  1611.                 inMenuBar : BEGIN
  1612.                     AdjustMenus;
  1613.                     DoMenuCommand( MenuSelect( event.where ) );
  1614.                 END; { inMenuBar }
  1615.                 
  1616.                 inSysWindow :
  1617.                     SystemClick( event, window );
  1618.                 
  1619.                 inContent :
  1620.                     IF window <> FrontWindow THEN BEGIN
  1621.                         SelectWindow(window);
  1622.                         {DoEvent(event);}    {use this line for "do first click"}
  1623.                     END ELSE
  1624.                         DoContentClick( window, event );
  1625.                 
  1626.                 inDrag :
  1627.                     DragWindow( window, event.where, screenBits.bounds );
  1628.                 
  1629.                 inGrow:
  1630.                     DoGrowWindow( window, event );
  1631.                 
  1632.                 inGoAway:
  1633.                     IF TrackGoAway( window, event.where ) THEN
  1634.                         ignore := DoCloseWindow( window ); { we don't care if cancelled }
  1635.                 
  1636.                 inZoomIn, inZoomOut:
  1637.                 
  1638.                     IF TrackBox(window, event.where, part) THEN
  1639.                         DoZoomWindow( window, part );
  1640.             END; { case }
  1641.         END; { mouseDown }
  1642.         
  1643.         keyDown, autoKey : BEGIN
  1644.             key := CHR( BAnd( event.message, charCodeMask ) );
  1645.             IF BAnd( event.modifiers, cmdKey ) <> 0 THEN BEGIN { Command key down }
  1646.                 IF event.what = keyDown THEN BEGIN
  1647.                     AdjustMenus; { enable/disable/check menu items properly }
  1648.                     DoMenuCommand( MenuKey( key ) );
  1649.                 END; { if }
  1650.             END ELSE
  1651.                 DoKeyDown( event );
  1652.         END; { keyDown } { call DoActivate with the window and... }
  1653.         
  1654.         activateEvt: { TRUE for activate, FALSE for deactivate }
  1655.             DoActivate( WindowPtr( event.message ), BAND( event.modifiers, activeFlag ) <> 0 );
  1656.         
  1657.         updateEvt: { call DoUpdate with the window to update }
  1658.             DoUpdate( WindowPtr( event.message ) );
  1659.             
  1660.         diskEvt:
  1661.             IF HiWrd(event.message) <> noErr THEN BEGIN
  1662.                 SetPt(aPoint, kDILeft, kDITop);
  1663.                 err := DIBadMount(aPoint, event.message);
  1664.             END;
  1665.  
  1666.         kOSEvent:
  1667.             CASE BAnd(BRotL( event.message, 8 ), $FF ) OF    { high byte of message }
  1668.                 kMouseMovedMessage:
  1669.                     DoIdle; { mouse moved is also an idle event }
  1670.                 
  1671.                 kSuspendResumeMessage: BEGIN
  1672.                     gInBackground := BAnd( event.message, kResumeMask ) = 0;
  1673.                     DoActivate( FrontWindow, NOT gInBackground );
  1674.                 END; { kSuspendResumeMessage }
  1675.         END; 
  1676.     END; { case }
  1677. END; { DoEvent }
  1678.  
  1679.  
  1680.  
  1681. {$S Main}
  1682. PROCEDURE EventLoop;
  1683.  
  1684. {    Get events forever, and handle them by calling DoEvent.
  1685.      Also call AdjustCursor each time through the loop. }
  1686.  
  1687. VAR
  1688.     cursorRgn        : RgnHandle;
  1689.     gotEvent        : BOOLEAN;
  1690.     event            : EventRecord;
  1691.     mouse            : Point;
  1692.  
  1693. BEGIN { EventLoop }
  1694.     cursorRgn := NewRgn; { we'll pass an empty region to WNE the first time thru }
  1695.     REPEAT
  1696.         IF gHasWaitNextEvent THEN BEGIN
  1697.             GetGlobalMouse(mouse);        {since we might go to sleep}
  1698.             AdjustCursor(mouse, cursorRgn);
  1699.             gotEvent := WaitNextEvent(everyEvent, event, GetSleep, cursorRgn)
  1700.         END ELSE BEGIN
  1701.             SystemTask;
  1702.             gotEvent := GetNextEvent(everyEvent, event);
  1703.         END; { if }
  1704.         IF gotEvent THEN BEGIN
  1705.             AdjustCursor(event.where, cursorRgn);
  1706.             DoEvent(event);
  1707.             END
  1708.         ELSE
  1709.             DoIdle;
  1710.     UNTIL FALSE; { loop forever }
  1711. END; { EventLoop }
  1712.  
  1713.  
  1714.  
  1715. PROCEDURE _DataInit; EXTERNAL;
  1716.  
  1717. {    This routine is automatically linked in by the MPW Linker. This external
  1718.     reference to it is done so that we can unload its segment, %A5Init. }
  1719.  
  1720.  
  1721. {$S Main}
  1722. BEGIN { main program }
  1723.     UnloadSeg( @_DataInit );    { note that _DataInit must not be in Main! }
  1724.     MaxApplZone;                { expand the heap so code segments load at the top }
  1725.     Initialize;                    { initialize the program }
  1726.     UnloadSeg( @Initialize );    { note that Initialize must not be in Main! }
  1727.      EventLoop;                    { call the main event loop }
  1728. END. { main program }
  1729.